package com.itheima.test2;

import com.itheima.test2.domain.Person;

import java.util.ArrayList;
import java.util.Scanner;

public class Operator {


    //查索引
    public int index(ArrayList<Person> list, String id) {
        for (int i = 0; i < list.size(); i++) {
            //list.get(i).getId()
            if (list.isEmpty() || id.equals(list.get(i).getId())) {
                return i;
            }
        }
        return -1;
    }

    //增
    public void addPerson(ArrayList<Person> list) {
        Scanner sc = new Scanner(System.in);

        String id = null;
        while (true) {
            System.out.println("请输入编号:");
            id = sc.next();
            if (index(list, id) == -1) {
                break;
            } else {
                System.out.println("编号已存在,请重输");
            }
        }
        System.out.println("请输入姓名:");
        String name = sc.next();
        System.out.println("请输入年龄:");
        int age = sc.nextInt();
        Person st = new Person(id, name, age);
        list.add(st);
    }

    //删
    public void removePerson(ArrayList<Person> list) {
        Scanner sc = new Scanner(System.in);
        if (list.isEmpty() || list.size() == 0) {
            System.out.println("系统中暂无信息!");
            return;
        }
        String id = null;
        while (true) {
            System.out.println("请输入编号:");
            id = sc.next();
            if (index(list, id) == -1) {
                System.out.println("系统中没有" + id);
                break;
            } else {
                list.remove(list.get(index(list, id)));
                System.out.println("删除成功!");
                break;

            }
        }


    }

    //改
    public void updatePerson(ArrayList<Person> list) {
        Scanner sc = new Scanner(System.in);
        if (list.isEmpty() || list.size() == 0) {
            System.out.println("系统中暂无信息!");
            return;
        }
        String id = null;
        while (true) {
            System.out.println("请输入编号:");
            id = sc.next();
            if (index(list, id) == -1) {
                System.out.println("系统中没有" + id);
                break;
            } else {
                System.out.println("请输入名字");
                list.get(index(list, id)).setName(sc.next());
                System.out.println("请输入年龄");
                list.get(index(list, id)).setAge(sc.nextInt());
                System.out.println("修改成功!");
                break;
            }
        }
    }

    //查
    public void queryAll(ArrayList<Person> list) {
        if (list.isEmpty() || list.size() == 0) {
            System.out.println("暂无信息!");
            return;
        }

        System.out.println("编号\t\t名字\t\t年龄");
        for (int i = 0; i < list.size(); i++) {
            //list.get(i)
            System.out.println(list.get(i).getId() + "\t\t"
                    + list.get(i).getName() + "\t\t"
                    + list.get(i).getAge());
        }

    }


}
